"use client"

import { useState, useEffect, useCallback, useMemo } from "react"
import { motion } from "framer-motion"
import { Search, Plus, Clock, Trophy, Star, TrendingUp, Users, Award, ChevronDown, Loader2, ChevronLeft, ChevronRight } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { HackCard } from "@/components/hack-card"
import { LoadingScreen } from "@/components/loading-screen"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { useTranslation } from "@/lib/i18n"
import { competitionsApi, Competition, PaginatedResponse } from "@/lib/api"
import { useAuth } from "@/contexts/auth-context"
import Link from "next/link"

const mockHackathons = [
  {
    id: 1,
    title: "Kaggle - House Prices Competition",
    platform: "Kaggle",
    prize: "$15,000",
    deadline: "2024-02-15",
    participants: 2847,
    image: "/default-competition.svg",
    tags: ["Machine Learning", "Regression", "Data Science"],
    difficulty: "Beginner",
    description: "预测房价的经典机器学习竞赛",
    submissions: 15420,
    teams: 3200,
    category: "machineLearning",
    type: "data",
  },
  {
    id: 2,
    title: "阿里天池 - 智慧城市AI挑战赛",
    platform: "天池",
    prize: "¥100,000",
    deadline: "2024-02-20",
    participants: 1523,
    image: "/default-competition.svg",
    tags: ["Computer Vision", "AI", "Smart City"],
    difficulty: "Advanced",
    description: "利用AI技术解决智慧城市问题",
    submissions: 8900,
    teams: 1200,
    category: "aiLlm",
    type: "data",
  },
  {
    id: 3,
    title: "Devpost - Climate Change Hackathon",
    platform: "Devpost",
    prize: "$25,000",
    deadline: "2024-02-18",
    participants: 892,
    image: "/default-competition.svg",
    tags: ["Sustainability", "Web Dev", "Mobile"],
    difficulty: "Intermediate",
    description: "用技术对抗气候变暖",
    submissions: 450,
    teams: 180,
    category: "webDevelopment",
    type: "hackathon",
  },
  {
    id: 4,
    title: "Google AI Challenge 2024",
    platform: "Google",
    prize: "$50,000",
    deadline: "2024-02-25",
    participants: 3421,
    image: "/default-competition.svg",
    tags: ["AI/ML", "TensorFlow", "Innovation"],
    difficulty: "Advanced",
    description: "Google官方AI创新挑战赛",
    submissions: 12000,
    teams: 2800,
    category: "aiLlm",
    type: "hackathon",
  },
  {
    id: 5,
    title: "Microsoft Azure Hackathon",
    platform: "Microsoft",
    prize: "$30,000",
    deadline: "2024-02-22",
    participants: 1876,
    image: "/default-competition.svg",
    tags: ["Cloud", "Azure", "Enterprise"],
    difficulty: "Intermediate",
    description: "基于Azure平台的企业级解决方案",
    submissions: 6700,
    teams: 1500,
    category: "webDevelopment",
    type: "hackathon",
  },
  {
    id: 6,
    title: "OpenAI GPT-4 创新大赛",
    platform: "OpenAI",
    prize: "$40,000",
    deadline: "2024-02-28",
    participants: 2156,
    image: "/default-competition.svg",
    tags: ["LLM", "GPT-4", "Innovation"],
    difficulty: "Advanced",
    description: "探索GPT-4的无限可能",
    submissions: 9800,
    teams: 2000,
    category: "aiLlm",
    type: "hackathon",
  },
]

const statsData = [
  { label: "activeCompetitions", value: "156", icon: Trophy, color: "text-yellow-400" },
  { label: "participants", value: "28.5K", icon: Users, color: "text-blue-400" },
  { label: "totalPrize", value: "$2.1M", icon: Award, color: "text-green-400" },
  { label: "successfulTeams", value: "1.2K", icon: TrendingUp, color: "text-purple-400" },
]

// 防抖Hook
function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => {
      clearTimeout(handler)
    }
  }, [value, delay])

  return debouncedValue
}

export default function HomePage() {
  const [isLoading, setIsLoading] = useState(true)
  const [isSearching, setIsSearching] = useState(false)
  const [competitions, setCompetitions] = useState<Competition[]>([])
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedCategory, setSelectedCategory] = useState("allCategories")
  const [selectedLevel, setSelectedLevel] = useState("allLevels")
  const [selectedPlatform, setSelectedPlatform] = useState("allPlatforms")
  const [selectedType, setSelectedType] = useState("all")
  const [sortBy, setSortBy] = useState<'latest' | 'prize' | 'popularity'>('latest')
  
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize] = useState(12) // 每页显示12个竞赛
  const [totalCompetitions, setTotalCompetitions] = useState(0)
  const [isLoadingMore, setIsLoadingMore] = useState(false)
  const [paginationInfo, setPaginationInfo] = useState({
    total: 0,
    total_pages: 0,
    has_next: false,
    has_prev: false
  })
  
  const { t } = useTranslation()
  const { isAuthenticated, isLoading: authLoading } = useAuth()
  
  // 防抖搜索查询
  const debouncedSearchQuery = useDebounce(searchQuery, 300)

  const categories = [
    { key: "allCategories", label: t("allCategories") },
    { key: "machineLearning", label: t("machineLearning") },
    { key: "webDevelopment", label: t("webDevelopment") },
    { key: "blockchain", label: t("blockchain") },
    { key: "dataScience", label: t("dataScience") },
    { key: "aiLlm", label: t("aiLlm") },
    { key: "mobileDev", label: t("mobileDev") },
    { key: "gamedev", label: t("gamedev") },
  ]

  const levels = [
    { key: "allLevels", label: t("allLevels") },
    { key: "beginner", label: t("beginner") },
    { key: "intermediate", label: t("intermediate") },
    { key: "advanced", label: t("advanced") },
  ]

  const platforms = [
    { key: "allPlatforms", label: t("allPlatforms") },
    { key: "Kaggle", label: "Kaggle" },
    { key: "天池", label: "天池" },
    { key: "Devpost", label: "Devpost" },
    { key: "Google", label: "Google" },
    { key: "Microsoft", label: "Microsoft" },
    { key: "OpenAI", label: "OpenAI" },
  ]

  const types = [
    { key: "all", label: "全部类型" },
    { key: "data", label: "数据竞赛" },
    { key: "hackathon", label: "开发黑客松" },
  ]

  // 标签相关状态
  const [hotKeywords, setHotKeywords] = useState<{tag: string, count: number, display_name: string}[]>([])
  const [isLoadingTags, setIsLoadingTags] = useState(false)

  // 获取标签数据的函数
  const fetchTags = useCallback(async () => {
    try {
      setIsLoadingTags(true)
      // 暂时使用模拟数据，因为API方法不存在
      const mockTags = [
        { tag: "AI", count: 25, display_name: "人工智能" },
        { tag: "Web", count: 18, display_name: "Web开发" },
        { tag: "Data", count: 15, display_name: "数据科学" }
      ]
      setHotKeywords(mockTags)
    } catch (error: unknown) {
      console.error("Failed to fetch tags:", error)
      // 如果API失败，使用默认标签
      setHotKeywords([
        {tag: "AI/ML", count: 0, display_name: "AI/ML"},
        {tag: "Web3", count: 0, display_name: "Web3"},
        {tag: "Climate Tech", count: 0, display_name: "Climate Tech"},
        {tag: "FinTech", count: 0, display_name: "FinTech"},
        {tag: "Healthcare", count: 0, display_name: "Healthcare"},
        {tag: "Gaming", count: 0, display_name: "Gaming"}
      ])
    } finally {
      setIsLoadingTags(false)
    }
  }, [])

  // 获取竞赛数据的函数
  const fetchCompetitions = useCallback(async (isInitialLoad = false, page = 1, isAppend = false) => {
    try {
      if (isInitialLoad) {
        setIsLoading(true)
      } else {
        setIsLoadingMore(true)
      }
      
      console.log("Fetching competitions with params:", {
        search: debouncedSearchQuery || undefined,
        category: selectedCategory !== "allCategories" ? selectedCategory : undefined,
        difficulty: selectedLevel !== "allLevels" ? selectedLevel : undefined,
        page: page,
        size: pageSize,
        isAppend
      })
      
      // 映射前端sortBy到后端sort_by
      const getSortBy = (sortBy: string) => {
        switch (sortBy) {
          case 'latest': return 'created_at'
          case 'prize': return 'prize_amount'
          case 'popularity': return 'participants_count'
          default: return 'created_at'
        }
      }
      
      const response = await competitionsApi.getCompetitions({
        search: debouncedSearchQuery || undefined,
        category: selectedCategory !== "allCategories" ? selectedCategory : undefined,
        difficulty: selectedLevel !== "allLevels" ? selectedLevel : undefined,
        sort_by: getSortBy(sortBy),
        sort_order: 'desc',
        page: page,
        size: pageSize
      })
      
      console.log("API response:", response)
      console.log("Response type:", typeof response)
      console.log("Items:", response?.items)
      console.log("Pagination:", response?.pagination)
      
      const competitionsData = response?.items || []
      const apiPaginationInfo = response?.pagination
      
      if (isAppend) {
        // 追加数据（加载更多）
        setCompetitions(prev => [...prev, ...competitionsData])
      } else {
        // 替换数据（页码跳转或初始加载）
        setCompetitions(competitionsData)
      }
      
      // 从分页信息中获取总数和分页状态
      if (apiPaginationInfo) {
        setTotalCompetitions(apiPaginationInfo.total)
        setPaginationInfo({
          total: apiPaginationInfo.total,
          total_pages: apiPaginationInfo.total_pages,
          has_next: apiPaginationInfo.has_next,
          has_prev: apiPaginationInfo.has_prev
        })
      }
      
    } catch (error) {
      console.error("Failed to fetch competitions:", error)
      console.error("Error details:", error instanceof Error ? error.message : String(error))
      // 如果API失败，使用模拟数据作为后备
      if (page === 1) {
        const convertedCompetitions: Competition[] = mockHackathons.map(hack => ({
          id: hack.id,
          title: hack.title,
          description: hack.description,
          url: `https://example.com/competition/${hack.id}`,
          platform: hack.platform,
          prize_pool: hack.prize,
          start_date: new Date().toISOString(),
          end_date: hack.deadline,
          submission_deadline: hack.deadline,
          max_participants: hack.participants,
          current_participants: hack.participants,
          participants_count: hack.participants,
          difficulty_level: hack.difficulty.toLowerCase() as 'beginner' | 'intermediate' | 'advanced',
          tags: hack.tags,
          image_url: hack.image,
          category: hack.category,
          status: 'active' as const,
          is_active: true,
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        }))
        setCompetitions(convertedCompetitions)
        setTotalCompetitions(convertedCompetitions.length)
      }
    } finally {
      if (isInitialLoad) {
        setIsLoading(false)
      } else {
        setIsLoadingMore(false)
      }
    }
  }, [debouncedSearchQuery, selectedCategory, selectedLevel, pageSize])

  // 初始加载
  useEffect(() => {
    if (!authLoading) {
      fetchCompetitions(true, 1)
    }
  }, [authLoading, fetchCompetitions])

  // 当搜索或筛选条件变化时重新获取数据
  useEffect(() => {
    if (!authLoading && !isLoading) {
      setCurrentPage(1) // 重置到第一页
      fetchCompetitions(false, 1)
    }
  }, [debouncedSearchQuery, selectedCategory, selectedLevel, selectedPlatform, selectedType, sortBy, authLoading, isLoading, fetchCompetitions])

  // 分页处理函数
  const handlePageChange = useCallback((page: number) => {
    setCurrentPage(page)
    fetchCompetitions(false, page, false) // 使用替换模式
    // 滚动到页面顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }, [fetchCompetitions])

  const handleLoadMore = useCallback(() => {
    const nextPage = currentPage + 1
    setCurrentPage(nextPage)
    fetchCompetitions(false, nextPage, true)
  }, [currentPage, fetchCompetitions])


  
  // 计算分页信息（优先使用API返回的信息）
  const totalPages = paginationInfo?.total_pages || Math.ceil(totalCompetitions / pageSize)
  const hasNextPage = paginationInfo?.has_next ?? (currentPage < totalPages)
  const hasPrevPage = paginationInfo?.has_prev ?? (currentPage > 1)

  // 直接使用API返回的数据，因为筛选和排序已在后端完成
  const filteredCompetitions = competitions || []

  // 处理热门关键词点击
  const handleKeywordClick = useCallback((keyword: string, e?: React.MouseEvent) => {
    if (e) {
      e.preventDefault()
    }
    setSearchQuery(keyword)
  }, [])

  // 清除所有筛选条件
  const handleClearFilters = useCallback((e?: React.MouseEvent) => {
    if (e) {
      e.preventDefault()
    }
    setSearchQuery("")
    setSelectedCategory("allCategories")
    setSelectedLevel("allLevels")
    setSelectedPlatform("allPlatforms")
    setSelectedType("all")
  }, [])

  // 处理筛选器变化
  const handleFilterChange = useCallback((filterType: string, value: string, e?: React.MouseEvent) => {
    if (e) {
      e.preventDefault()
    }
    switch (filterType) {
      case 'type':
        setSelectedType(value)
        break
      case 'category':
        setSelectedCategory(value)
        break
      case 'level':
        setSelectedLevel(value)
        break
      case 'platform':
        setSelectedPlatform(value)
        break
    }
  }, [])

  if (isLoading) {
    return <LoadingScreen />
  }

  return (
    <div className="min-h-screen pt-20">
      {/* Hero Section */}
      <motion.section
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="container mx-auto px-4 py-12"
      >
        <div className="text-center mb-12">
          <motion.h1
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ delay: 0.2 }}
            className="text-responsive-4xl font-bold mb-6 text-gradient-animate"
          >
            发现最酷的竞赛
          </motion.h1>
          <motion.p
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.4 }}
            className="text-responsive-xl text-white mb-8"
          >
            加入全球开发者社区，参与激动人心的编程挑战
          </motion.p>

          {/* 统计数据 */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.5 }}
            className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8"
          >
            {statsData.map((stat, index) => (
              <motion.div
                key={stat.label}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.6 + index * 0.1 }}
                className="glass-light rounded-lg p-4 card-hover"
              >
                <div className="flex items-center justify-center mb-2">
                  <stat.icon className={`w-6 h-6 ${stat.color}`} />
                </div>
                <div className={`text-2xl font-bold ${stat.color} mb-1`}>{stat.value}</div>
                <div className="text-sm text-white">{t(stat.label as any)}</div>
              </motion.div>
            ))}
          </motion.div>

          {/* 搜索栏 */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.8 }}
            className="max-w-4xl mx-auto mb-6"
          >
            <form 
              onSubmit={(e) => {
                e.preventDefault() // 阻止表单提交和页面刷新
              }}
              className="relative"
            >
              <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-white w-5 h-5" />
              {isSearching && (
                <Loader2 className="absolute right-4 top-1/2 transform -translate-y-1/2 text-white w-5 h-5 animate-spin" />
              )}
              <Input
                placeholder="搜索竞赛、标签或平台..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    e.preventDefault() // 双重保护，防止页面刷新
                  }
                }}
                className="pl-12 pr-12 py-4 text-lg glass-light border-0 focus:ring-2 focus:ring-blue-500 text-white placeholder-gray-300"
              />
            </form>
          </motion.div>

          {/* 筛选器 */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 1 }}
            className="flex flex-wrap justify-center gap-4 mb-8"
          >
            {/* 竞赛类型 */}
            <DropdownMenu modal={false}>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" className="bg-transparent text-white border-gray-500 hover:border-blue-400">
                  {types.find((t) => t.key === selectedType)?.label}
                  <ChevronDown className="w-4 h-4 ml-2" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="filter-dropdown">
                {types.map((type) => (
                  <DropdownMenuItem
                    key={type.key}
                    onClick={(e) => handleFilterChange('type', type.key, e)}
                    className="text-white hover:bg-white/10 cursor-pointer"
                  >
                    {type.label}
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>

            {/* 分类筛选 */}
            <DropdownMenu modal={false}>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" className="bg-transparent text-white border-gray-500 hover:border-blue-400">
                  {categories.find((c) => c.key === selectedCategory)?.label}
                  <ChevronDown className="w-4 h-4 ml-2" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="filter-dropdown">
                {categories.map((category) => (
                  <DropdownMenuItem
                    key={category.key}
                    onClick={(e) => handleFilterChange('category', category.key, e)}
                    className="text-white hover:bg-white/10 cursor-pointer"
                  >
                    {category.label}
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>

            {/* 难度筛选 */}
            <DropdownMenu modal={false}>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" className="bg-transparent text-white border-gray-500 hover:border-blue-400">
                  {levels.find((l) => l.key === selectedLevel)?.label}
                  <ChevronDown className="w-4 h-4 ml-2" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="filter-dropdown">
                {levels.map((level) => (
                  <DropdownMenuItem
                    key={level.key}
                    onClick={(e) => handleFilterChange('level', level.key, e)}
                    className="text-white hover:bg-white/10 cursor-pointer"
                  >
                    {level.label}
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>

            {/* 平台筛选 */}
            <DropdownMenu modal={false}>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" className="bg-transparent text-white border-gray-500 hover:border-blue-400">
                  {platforms.find((p) => p.key === selectedPlatform)?.label}
                  <ChevronDown className="w-4 h-4 ml-2" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="filter-dropdown">
                {platforms.map((platform) => (
                  <DropdownMenuItem
                    key={platform.key}
                    onClick={(e) => handleFilterChange('platform', platform.key, e)}
                    className="text-white hover:bg-white/10 cursor-pointer"
                  >
                    {platform.label}
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>
          </motion.div>

          {/* 热门关键词 */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 1.2 }}
            className="flex flex-wrap justify-center gap-2 mb-8"
          >
            {/* 清除按钮 */}
            <motion.div
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: 1.3 }}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
            >
              <Badge
                variant="outline"
                className="cursor-pointer hover:bg-red-500/20 transition-all duration-300 text-white border-gray-500 hover:border-red-400 hover:text-red-300"
                onClick={(e) => handleClearFilters(e)}
              >
                清除筛选
              </Badge>
            </motion.div>
            
            {/* 标签列表 */}
            {isLoadingTags ? (
              <div className="text-white">加载标签中...</div>
            ) : (
              hotKeywords.map((tag, index) => (
                <motion.div
                  key={tag.tag}
                  initial={{ opacity: 0, scale: 0.8 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ delay: 1.4 + index * 0.1 }}
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                >
                  <Badge
                    variant="outline"
                    className="cursor-pointer hover:bg-blue-500/20 transition-all duration-300 text-white border-gray-500 hover:border-blue-400 hover:text-blue-300"
                    onClick={(e) => handleKeywordClick(tag.tag, e)}
                  >
                    {tag.display_name}
                  </Badge>
                </motion.div>
              ))
            )}
          </motion.div>
        </div>

        {/* 精选竞赛横向滚动 */}
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ delay: 1.4 }}
          className="mb-12"
        >
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-responsive-2xl font-bold flex items-center gap-2 text-white">
              <Star className="w-6 h-6 text-yellow-400" />
              精选竞赛
            </h2>
            <Button variant="ghost" size="sm" className="text-white hover:text-blue-300">
              查看全部
            </Button>
          </div>
          <div className="flex gap-6 overflow-x-auto pb-4 scrollbar-hide">
            {(() => {
              // 筛选出官方精选的竞赛（奖金高、参与人数多的竞赛）
              const featuredComps = filteredCompetitions
                .filter(comp => {
                  const prizeAmount = typeof comp.prize_pool === 'number' ? comp.prize_pool : 0
                  const participants = comp.participants_count || 0
                  return prizeAmount > 10000 || participants > 1000
                })
                .slice(0, 3)
              
              // 如果没有符合条件的，就取前3个
              const displayComps = featuredComps.length > 0 ? featuredComps : filteredCompetitions.slice(0, 3)
              
              return displayComps.map((competition, index) => (
                <motion.div
                  key={competition.id}
                  initial={{ opacity: 0, x: 20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 1.6 + index * 0.1 }}
                  className="flex-shrink-0 w-80"
                >
                  <HackCard hackathon={{
                    ...competition,
                    difficulty: competition.difficulty_level,
                    deadline: competition.end_date,
                    participants: competition.current_participants || 0,
                    image: competition.image_url || '/default-competition.svg',
                    prize: competition.prize_pool,
                    submissions: 0,
                    teams: 0,
                    type: 'hackathon'
                  }} featured />
                </motion.div>
              ))
            })()}
          </div>
        </motion.div>

        {/* 即将截止 */}
        <motion.div
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ delay: 1.8 }}
          className="mb-12"
        >
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-responsive-2xl font-bold flex items-center gap-2 text-white">
              <Clock className="w-6 h-6 text-red-400" />
              即将截止
            </h2>
            <Button variant="ghost" size="sm" className="text-white hover:text-blue-300">
              查看全部
            </Button>
          </div>
          <div className="flex gap-6 overflow-x-auto pb-4 scrollbar-hide">
            {(() => {
              // 筛选出即将截止的竞赛（7天内截止的）
              const urgentComps = filteredCompetitions
                .filter(comp => {
                  const deadline = comp.submission_deadline || comp.end_date
                  if (!deadline) return false
                  
                  const deadlineDate = new Date(deadline)
                  const now = new Date()
                  const diffTime = deadlineDate.getTime() - now.getTime()
                  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
                  
                  // 7天内截止且还未截止的竞赛
                  return diffDays > 0 && diffDays <= 7
                })
                .sort((a, b) => {
                  // 按截止时间排序，最紧急的在前
                  const deadlineA = a.submission_deadline || a.end_date
                  const deadlineB = b.submission_deadline || b.end_date
                  return new Date(deadlineA || '').getTime() - new Date(deadlineB || '').getTime()
                })
                .slice(0, 3)
              
              // 如果没有即将截止的，就显示最近的3个
              const displayComps = urgentComps.length > 0 ? urgentComps : filteredCompetitions.slice(0, 3)
              
              return displayComps.map((competition, index) => (
                <motion.div
                  key={competition.id}
                  initial={{ opacity: 0, x: 20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 2 + index * 0.1 }}
                  className="flex-shrink-0 w-80"
                >
                  <HackCard hackathon={{
                    ...competition,
                    difficulty: competition.difficulty_level,
                    deadline: competition.end_date,
                    participants: competition.current_participants || 0,
                    image: competition.image_url || '/default-competition.svg',
                    prize: competition.prize_pool,
                    submissions: 0,
                    teams: 0,
                    type: 'hackathon'
                  }} urgent />
                </motion.div>
              ))
            })()}
          </div>
        </motion.div>

        {/* 全部竞赛瀑布流 */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 2.2 }}>
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-responsive-2xl font-bold flex items-center gap-2 text-white">
              <Trophy className="w-6 h-6 text-purple-400" />
              全部竞赛 ({totalCompetitions})
            </h2>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                className={`bg-transparent text-white border-gray-500 hover:border-blue-400 hover:text-blue-300 ${
                  sortBy === 'latest' ? 'border-blue-400 text-blue-300' : ''
                }`}
                onClick={(e) => {
                  e.preventDefault()
                  setSortBy('latest')
                }}
              >
                最新
              </Button>
              <Button
                variant="outline"
                size="sm"
                className={`bg-transparent text-white border-gray-500 hover:border-blue-400 hover:text-blue-300 ${
                  sortBy === 'prize' ? 'border-blue-400 text-blue-300' : ''
                }`}
                onClick={(e) => {
                  e.preventDefault()
                  setSortBy('prize')
                }}
              >
                奖金
              </Button>
              <Button
                variant="outline"
                size="sm"
                className={`bg-transparent text-white border-gray-500 hover:border-blue-400 hover:text-blue-300 ${
                  sortBy === 'popularity' ? 'border-blue-400 text-blue-300' : ''
                }`}
                onClick={(e) => {
                  e.preventDefault()
                  setSortBy('popularity')
                }}
              >
                热度
              </Button>
            </div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredCompetitions.map((competition, index) => (
              <motion.div
                key={competition.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 2.4 + index * 0.1 }}
              >
                <HackCard hackathon={{
                  ...competition,
                  difficulty: competition.difficulty_level,
                  deadline: competition.end_date,
                  participants: competition.current_participants || 0,
                  image: competition.image,
                  banner_image: competition.banner_image,
                  prize: competition.prize_pool,
                  submissions: 0,
                  teams: 0,
                  type: 'hackathon'
                }} />
              </motion.div>
            ))}
          </div>

          {filteredCompetitions.length === 0 && (
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="text-center py-12">
              <div className="text-6xl mb-4">🔍</div>
              <h3 className="text-xl font-semibold text-white mb-2">没有找到匹配的竞赛</h3>
              <p className="text-gray-300">尝试调整筛选条件或搜索关键词</p>
            </motion.div>
          )}
        </motion.div>
      </motion.section>

      {/* 悬浮开黑按钮 */}
      <motion.div
        initial={{ opacity: 0, scale: 0 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ delay: 2.5 }}
        className="fixed bottom-8 right-8 z-50"
      >
        {authLoading ? (
          <motion.div whileHover={{ scale: 1.05 }}>
            <Button
              size="lg"
              disabled
              className="rounded-full w-16 h-16 bg-gradient-to-r from-gray-500 to-gray-600 shadow-lg cursor-not-allowed"
              title="正在加载..."
            >
              <div className="w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin" />
            </Button>
          </motion.div>
        ) : (
          <Link href={isAuthenticated ? "/lobby" : "/auth/login"}>
            <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
              <Button
                size="lg"
                className="rounded-full w-16 h-16 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 shadow-lg pulse-neon float-animation"
                title={isAuthenticated ? "进入开黑大厅" : "登录后进入开黑大厅"}
              >
                <Plus className="w-8 h-8" />
              </Button>
            </motion.div>
          </Link>
        )}
      </motion.div>

      {/* 分页组件 */}
      {!isLoading && competitions.length > 0 && (
        <section className="py-8">
          <div className="container mx-auto px-4">
            <div className="flex flex-col items-center space-y-4">
              {/* 分页信息 */}
              <div className="text-sm text-gray-600 dark:text-gray-400">
                显示第 {Math.min((currentPage - 1) * pageSize + 1, totalCompetitions)} - {Math.min(currentPage * pageSize, totalCompetitions)} 项，共 {totalCompetitions} 项竞赛
              </div>
              
              {/* 分页按钮 */}
              <div className="flex items-center space-x-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handlePageChange(currentPage - 1)}
                  disabled={!hasPrevPage || isLoadingMore}
                  className="flex items-center space-x-1"
                >
                  <ChevronLeft className="h-4 w-4" />
                  <span>上一页</span>
                </Button>
                
                {/* 页码按钮 */}
                <div className="flex items-center space-x-1">
                  {Array.from({ length: Math.min(totalPages, 5) }, (_, i) => {
                    let pageNum
                    if (totalPages <= 5) {
                      pageNum = i + 1
                    } else if (currentPage <= 3) {
                      pageNum = i + 1
                    } else if (currentPage >= totalPages - 2) {
                      pageNum = totalPages - 4 + i
                    } else {
                      pageNum = currentPage - 2 + i
                    }
                    
                    return (
                      <Button
                        key={pageNum}
                        variant={currentPage === pageNum ? "default" : "outline"}
                        size="sm"
                        onClick={() => handlePageChange(pageNum)}
                        disabled={isLoadingMore}
                        className="min-w-[40px]"
                      >
                        {pageNum}
                      </Button>
                    )
                  })}
                </div>
                
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handlePageChange(currentPage + 1)}
                  disabled={!hasNextPage || isLoadingMore}
                  className="flex items-center space-x-1"
                >
                  <span>下一页</span>
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
              
              {/* 加载更多按钮（可选） */}
              {hasNextPage && (
                <Button
                  variant="ghost"
                  onClick={handleLoadMore}
                  disabled={isLoadingMore}
                  className="flex items-center space-x-2"
                >
                  {isLoadingMore ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      <span>加载中...</span>
                    </>
                  ) : (
                    <span>加载更多</span>
                  )}
                </Button>
              )}
            </div>
          </div>
        </section>
      )}
    </div>
  )
}
